package cn.qiao.linux;

import com.jcraft.jsch.*;

import java.io.InputStream;
import java.io.OutputStream;

public class ScpFromBToA {
    public static void main(String[] args) {
        String userA = "userA";
        String hostA = "hostA";
        String passwordA = "passwordA";

        String userB = "userB";
        String hostB = "hostB";
        String passwordB = "passwordB";
        String remoteFileB = "/path/to/file/on/B";
        String destinationOnA = "/path/to/destination/on/A";

        try {
            // 1. 连接到服务器A
            JSch jsch = new JSch();
            Session session = jsch.getSession(userA, hostA, 22);
            session.setPassword(passwordA);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();

            // 2. 在服务器A上执行SCP命令，从服务器B复制文件
            String scpCommand = String.format("scp %s@%s:%s %s", userB, hostB, remoteFileB, destinationOnA);
            ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
            channelExec.setCommand(scpCommand);

            // 3. 处理SCP命令中的密码输入
            OutputStream out = channelExec.getOutputStream();
            InputStream in = channelExec.getInputStream();
            channelExec.connect();

            // 4. 等待密码提示并输入密码
            byte[] tmp = new byte[1024];
            while (true) {
                while (in.available() > 0) {
                    int i = in.read(tmp, 0, 1024);
                    if (i < 0) break;
                    String response = new String(tmp, 0, i);
                    if (response.contains("password:")) {
                        out.write((passwordB + "\n").getBytes());
                        out.flush();
                    }
                }
                if (channelExec.isClosed()) {
                    break;
                }
                Thread.sleep(1000);
            }

            // 5. 关闭通道和会话
            channelExec.disconnect();
            session.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
